package com.paishen.peiniwan.module.profile;

import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.paishen.common.util.BaseUtil;
import com.paishen.peiniwan.BaseActivity;
import com.paishen.peiniwan.C;
import com.paishen.peiniwan.R;
import com.paishen.peiniwan.frame.PnwOkCallbackAdapter;
import com.paishen.peiniwan.frame.RecyclerAdapter;
import com.paishen.peiniwan.frame.http.PnwHttpManager;
import com.paishen.peiniwan.frame.http.entity.BalanceRecord;
import com.paishen.peiniwan.frame.http.entity.User;
import com.paishen.peiniwan.frame.http.response.HttpRespData;
import com.paishen.common.widget.MaterialHeader;
import com.paishen.common.widget.TitleLayout;
import com.squareup.okhttp.Request;

import java.util.ArrayList;
import java.util.List;

import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;

/**
 * Created by peng on 2015/12/17.
 */
public class ProfileBalanceDetailActivity extends BaseActivity {

    private TitleLayout layTitle;
    private PtrFrameLayout layPtrFrame;
    private RecyclerView viewRecycler;
    private LinearLayoutManager layoutManager;
    private BalanceDetailAdapter adapter;

    private int currPage = 1;
    private boolean reqLoad;
    private boolean fetchOver = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.frame_activity_common_list);
        layTitle = (TitleLayout) findViewById(R.id.lay_title);
        layTitle.pushContent(makeBackView(), getString(R.string.balance_detail), null, false);

        viewRecycler = (RecyclerView) findViewById(R.id.view_recycler);
        viewRecycler.setLayoutManager(layoutManager = new LinearLayoutManager(this));
        viewRecycler.setAdapter(adapter = new BalanceDetailAdapter());
        viewRecycler.setItemAnimator(new DefaultItemAnimator());
        viewRecycler.addItemDecoration(new RecyclerView.ItemDecoration() {
            int spacing = BaseUtil.dip2px(10);

            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.top = spacing;
            }
        });
        viewRecycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            private boolean scrollDown = false;

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                scrollDown = dy > 0;
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_IDLE:
                        int lastVisibleItem = layoutManager.findLastCompletelyVisibleItemPosition();
                        int totalItemCount = layoutManager.getItemCount();
                        if (!fetchOver && scrollDown && lastVisibleItem >= (totalItemCount - 1)) {
                            requestWalletGetBalanceDetail();
                        }
                        break;
                }
            }
        });

        layPtrFrame = (PtrFrameLayout) findViewById(R.id.lay_ptr_frame);
        MaterialHeader header = new MaterialHeader(this);
        int[] colors = new int[]{0xFF05131A};
        header.setColorSchemeColors(colors);
        header.setLayoutParams(new PtrFrameLayout.LayoutParams(-1, -2));
        header.setPadding(0, BaseUtil.dip2px(15), 0, BaseUtil.dip2px(10));
        header.setPtrFrameLayout(layPtrFrame);
        layPtrFrame.setDurationToCloseHeader(1500);
        layPtrFrame.setHeaderView(header);
        layPtrFrame.addPtrUIHandler(header);
        layPtrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, viewRecycler, header);
            }

            @Override
            public void onRefreshBegin(final PtrFrameLayout frame) {
                currPage = 1;
                requestWalletGetBalanceDetail();
            }
        });

        layPtrFrame.postDelayed(runRequest, 500);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        layPtrFrame.removeCallbacks(runRequest);
    }

    private Runnable runRequest = new Runnable() {
        @Override
        public void run() {
            layPtrFrame.autoRefresh();
        }
    };

    static class BalanceDetailAdapter extends RecyclerAdapter {
        public class ViewHolderItem extends RecyclerView.ViewHolder {
            public ViewHolderItem(View view) {
                super(view);
            }

            private TextView txType, txUsername, txCoupon, txCouponValue,
                    txPayType, txPayCoupon, txPayValue, txSerialId, txPayTime;
            private BalanceRecord bd;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            switch (viewType) {
                case Element.TYPE_ITEM:
                    View viewItem = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_profile_balance_detail, parent, false);
                    ViewHolderItem vhItem = new ViewHolderItem(viewItem);
                    vhItem.txType = (TextView) viewItem.findViewById(R.id.tx_type);
                    vhItem.txUsername = (TextView) viewItem.findViewById(R.id.tx_username);
                    vhItem.txCoupon = (TextView) viewItem.findViewById(R.id.tx_coupon);
                    vhItem.txCouponValue = (TextView) viewItem.findViewById(R.id.tx_coupon_value);
                    vhItem.txPayType = (TextView) viewItem.findViewById(R.id.tx_pay_type);
                    vhItem.txPayCoupon = (TextView) viewItem.findViewById(R.id.tx_pay_coupon);
                    vhItem.txPayValue = (TextView) viewItem.findViewById(R.id.tx_date_pay_value);
                    vhItem.txSerialId = (TextView) viewItem.findViewById(R.id.tx_serial_id);
                    vhItem.txPayTime = (TextView) viewItem.findViewById(R.id.tx_pay_time);
                    return vhItem;
            }

            return super.onCreateViewHolder(parent, viewType);
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            super.onBindViewHolder(holder, position);
            Element e = elements.get(position);
            switch (e.type) {
                case Element.TYPE_ITEM:
                    ViewHolderItem vhItem = (ViewHolderItem) holder;
                    vhItem.bd = (BalanceRecord) e.element;
                    boolean isSelfCreator = vhItem.bd.type == BalanceRecord.TYPE_DATE_CREATOR;
                    vhItem.txType.setText(isSelfCreator ? R.string.balance_record_type_1 : R.string.balance_record_type_2);
                    vhItem.txUsername.setText(vhItem.bd.target);
                    vhItem.txCoupon.setTextColor(vhItem.bd.price < 0 ? 0xFF05131A : 0xFFB3B3B3);
                    boolean hasCoupon = vhItem.bd.coupon_amount != null;
                    int mCouponValue = hasCoupon ? (int) vhItem.bd.coupon_amount.floatValue() : 0;
                    String strCouponValue = (mCouponValue > 0 ? "-" : "") + vhItem.itemView.getContext().getString(R.string.balance_record_date_pay_value, mCouponValue);
                    vhItem.txCouponValue.setText(strCouponValue);
                    vhItem.txCouponValue.setTextColor(vhItem.bd.price < 0 ? 0xFF05131A : 0xFFB3B3B3);
                    vhItem.txPayType.setText(vhItem.bd.price < 0 ? R.string.balance_record_pay_1 : R.string.balance_record_pay_2);
                    vhItem.txPayCoupon.setVisibility(hasCoupon ? View.VISIBLE : View.GONE);
                    String strPriceValue = vhItem.itemView.getContext().getString(R.string.balance_record_date_pay_value, (int) vhItem.bd.price);
                    if (vhItem.bd.price > 0) strPriceValue = "+" + strPriceValue;
                    vhItem.txPayValue.setText(strPriceValue);
                    vhItem.txSerialId.setText(vhItem.bd.serial_id);
                    vhItem.txPayTime.setText(vhItem.bd.pay_date);
                    break;
            }
        }
    }

    private void requestWalletGetBalanceDetail() {
        if (reqLoad) return;
        reqLoad = true;

        if (currPage > 1) adapter.refreshLoadState(true);
        PnwHttpManager.Wallet.getBalanceDetail(TAG, currPage, new PnwOkCallbackAdapter<HttpRespData<List<BalanceRecord>>>() {
            @Override
            public void onResponse(HttpRespData<List<BalanceRecord>> response, boolean fresh) {
                super.onResponse(response, fresh);
                layPtrFrame.refreshComplete();
                reqLoad = false;
                fetchOver = false;

                if (response.errcode == C.http.RESULT_SUCCESS) {
                    if (response.data != null && response.data.size() > 0) {
                        fetchOver = response.data.size() < BalanceDetailAdapter.FETCH_COUNT;
                        boolean b = currPage == 1 ? adapter.set(response.data, fetchOver) : adapter.append(response.data, fetchOver);
                        currPage++;
                    } else {
                        BaseUtil.showToast(response.errmsg);
                        fetchOver = true;
                        boolean b = currPage != 1 ? adapter.refreshLoadState(false) : adapter.set(new ArrayList<User>(), true);
                    }
                } else {
                    if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                            response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                        BaseUtil.showToast(response.errmsg);
                    }
                    adapter.refreshLoadState(false);
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                super.onFailure(request, e);
                layPtrFrame.refreshComplete();
                reqLoad = false;
                adapter.refreshLoadState(false);
            }
        });
    }
}
